#include "udp_server.hpp"
#include"err.hpp"
#include<memory>

using namespace ns_server;
using namespace std;

//使用手册
//   ./udp_server port
static void usage(string proc)
{
    cout<<"Usage:\n\t"<<proc<<" port\n"<<std::endl;
}

//小写转大写函数
std::string transation(std::string message)
{
    std::string responce;
    for(auto ch:message)
    {
        if(islower(ch))
            responce+=toupper(ch);
        else
            responce+=ch;
    }
    return responce;
}

//安全检查
static bool isSafe(std::string &command)
{
    auto pos = command.find("mv");
    if(pos!=std::string::npos) return false;
    pos = command.find("kill");
    if(pos!=std::string::npos) return false;
    pos = command.find("rm");
    if(pos!=std::string::npos) return false;
    pos = command.find("su");
    if(pos!=std::string::npos) return false;
    pos = command.find("sudo");
    if(pos!=std::string::npos) return false;

    return true;
}


//命令解释器
std::string executeCommand(std::string command)
{
    //1. 安全检查
    if(!isSafe(command)) return "You are a bad man!";

    //2. 执行命令
    FILE*fp=popen(command.c_str(),"r");
    if(fp==nullptr) return "None";

    std::string responce;
    char buffer[2048];
    while(fgets(buffer,sizeof(buffer),fp)!=nullptr)
        responce+=buffer;

    pclose(fp);

    return responce;
}

int main(int argc,char*argv[])
{
    if(argc!=2)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    //提取参数中的端口号
    uint16_t port=atoi(argv[1]);

    unique_ptr<UdpServer> usvr(new UdpServer(port,executeCommand));
    usvr->InitServer();
    usvr->Start();

    return 0;
}